<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Task extends Model
{
    use HasFactory, SoftDeletes;

    const STATUS_INITIALIZED = 1;
    const STATUS_PROGRESSING = 2;
    const STATUS_COMPLETED = 3;
    const STATUS_POSTPONED = 4;
    const STATUS_CANCELLED = 5;

    const NOTIFY_TYPE_SMS = 1;

    protected $fillable = ['sheet_template_id', 'task_template_id', 'frequency', 'year', 'key'];

    protected $hidden = ['deleted_at'];

    public function progressing(): Attribute
    {
        return Attribute::make(
            get: function () {
                $subTaskCount = $this->subTasks()->count();
                if ($subTaskCount) {
                    return round($this->subTasks()->whereStatus(SubTask::STATUS_COMPLETED)->count() / $subTaskCount, 2);
                }
                return 0;
            }
        );
    }

    public function districts(): Attribute
    {
        return Attribute::make(
            get: function () {
                return District::whereIn('id', $this->subTasks()->pluck('district_id'))->get();
            }
        );
    }

    public function sheetTemplate()
    {
        return $this->belongsTo(SheetTemplate::class);
    }

    public function taskTemplate()
    {
        return $this->belongsTo(TaskTemplate::class);
    }

    public function subTasks()
    {
        return $this->hasMany(SubTask::class)->select(['id', 'task_id', 'district_id', 'status', 'data']);
    }
}
